using System;
using System.Data;
using NHibernate;
using NHibernate.UserTypes;
using NHibernate.SqlTypes;

namespace Caramel.NHibernate.UserTypes
{
	public class EncryptedStringType : IUserType
	{
		private readonly SqlType[] sqlTypes = new SqlType[] { new StringSqlType() };

		//            public IEncryptor Encryptor { get; set; }

		#region IUserType Members

		public new bool Equals(object x, object y)
		{
			return x == y;
		}

		public int GetHashCode(object x)
		{
			return x.GetHashCode();
		}

		public object NullSafeGet(IDataReader rs, string[] names, object owner)
		{
			string value = (string)NHibernateUtil.String.NullSafeGet(rs, names[0]);

			if (String.IsNullOrEmpty(value))
			{
				return value;
			}

			// TODO: TryResolve???
			//return Container.Resolve<IEncryptor>().Decrypt(value);

			throw new NotImplementedException();
		}

		public void NullSafeSet(IDbCommand cmd, object value, int index)
		{
			if (value == null)
			{
				NHibernateUtil.String.NullSafeSet(cmd, null, index);
			}
			else
			{
				throw new NotImplementedException();

				// TODO: TryResolve???
				//NHibernateUtil.String.NullSafeSet(cmd, Container.Resolve<IEncryptor>().Encrypt((string)value), index);
			}
		}

		public object DeepCopy(object value)
		{
			return value;
		}

		public object Replace(object original, object target, object owner)
		{
			return original;
		}

		public object Assemble(object cached, object owner)
		{
			return cached;
		}

		public object Disassemble(object value)
		{
			return value;
		}

		public SqlType[] SqlTypes
		{
			get { return sqlTypes; }
		}

		public Type ReturnedType
		{
			get { return typeof(string); }
		}

		public bool IsMutable
		{
			get { return false; }
		}

		#endregion
	}
}
